package com.aegis.autodeployplugin.tasks;

import com.aegis.autodeployplugin.AutoDeployPlugin;
import com.aegis.autodeployplugin.api.RetrofitUtil;
import com.aegis.autodeployplugin.entity.response.BaseResponse;
import com.aegis.autodeployplugin.entity.extension.UploadExtension;
import com.aegis.autodeployplugin.entity.response.UploadResponse;
import com.aegis.autodeployplugin.entity.params.DingTalkLinkModel;
import com.aegis.autodeployplugin.service.ApiService;
import com.android.build.gradle.api.ApplicationVariant;
import com.android.build.gradle.api.BaseVariant;
import com.android.build.gradle.api.BaseVariantOutput;

import org.apache.http.util.TextUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Response;

/**
 * desc     :
 *
 * @author : Aegis_Lee
 * date     : 2021/7/17
 * email    : 476810504@qq.com
 */
public class PgyUploadTask extends DefaultTask {
    private UploadExtension mUploadParam;
    private BaseVariant mBaseVariant;

    public void init(UploadExtension mUploadParam, ApplicationVariant variant){
        this.mUploadParam = mUploadParam;
        this.mBaseVariant = variant;
        setDescription("upload apk to pgy");
        setGroup(AutoDeployPlugin.PLUGIN_EXTENSION_NAME);
    }

    @TaskAction
    public void uploadApk(){
        for (BaseVariantOutput baseVariantOutput : mBaseVariant.getOutputs()){
            File outputFile = baseVariantOutput.getOutputFile();
            if (null == outputFile || !outputFile.exists()){
                throw new GradleException("Release apk is not exists");
            }

            System.out.println("上传apk到蒲公英：" + outputFile.getAbsolutePath());

            upload(mUploadParam.pgyApiKey, mUploadParam.pgyUpdateDesc, outputFile);
        }
    }

    private void upload(String apiKey, String updateDesc, File file) {
        try {
            Response<BaseResponse<UploadResponse>> response = RetrofitUtil.getInstance()
                    .create("https://www.pgyer.com")
                    .create(ApiService.class)
                    .upload(apiKey,
                            MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(file, MediaType.parse("multipart/form-data"))),
                            2,
                            "123456",
                            updateDesc,
                            "")
                    .execute();
            UploadResponse uploadResponse = response.body().getData();
            System.out.println(uploadResponse);

            if (TextUtils.isEmpty(uploadResponse.getBuildShortcutUrl())){
                System.out.println("短链接为空");
                return;
            }

            // 上传完成，进行通知
            String shortUrl = String.format("https://pgyer.com/%s", uploadResponse.getBuildShortcutUrl());
            NotifyTask.setDingTalkParams(new DingTalkLinkModel(mUploadParam.dingTalkTitle, mUploadParam.dingTalkDesc,
                    uploadResponse.getBuildQRCodeURL(), shortUrl));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
